<template>
  <div
      class="custom-image"
      :class="{
        'highlight-default': isHighlight
      }"
      ref="customImage"
      style="width: 80px;
        height: 95px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        position: relative;">
    <img class="custom-image-icon"
         :src="iconSrc"
         style="width: 50px;
            height: 50px;
            display: block;
            position: relative;
            margin: 0 auto;
            pointer-events: none;"/>
    <el-tooltip :content="label" placement="right" effect="light">
      <div class="custom-image-label"
           style="width: 100%;
              color: rgba(44, 49, 59, 1);
              text-align: center;
              margin-top: 8px;
              text-overflow: ellipsis;
              white-space: nowrap;
              word-break: keep-all;
              overflow: hidden;
              font-size: 12px;
              line-height: 12px;
              height: 12px;">
        {{ label }}
      </div>
    </el-tooltip>
  </div>
</template>

<script>
import StartIcon from "../../../assets/nodeIcon/start.png";

export default {
  inject: ['getNode', 'getGraph'],
  props: {
    position: {
      type: String,
      default: 'graph',
      validator: (val) => {
        return ['sidePanel', 'graph'].find(item => item === val)
      }
    },
    nodeData: Object
  },

  data() {
    return {
      StartIcon,
      iconSrc: '#',
      label: '',
      node: null,
      graph: null,

      isHighlight: false,
    }
  },

  mounted() {
    if (this.position === 'graph') {
      this.initNodeForGraph()
    }

    if (this.position === 'sidePanel') {
      this.initNodeForSidePanel()
    }
  },

  methods: {
    getBase64ImgSrc(imgLocalSrc) {
      return new Promise(resolve => {
        const img = document.createElement('img');
        img.src = imgLocalSrc;
        img.onload = function () {
          const canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height
          const ctx = canvas.getContext("2d")
          ctx.drawImage(img, 0, 0, img.width, img.height)
          const dataURL = canvas.toDataURL("image/png")

          resolve(dataURL)
        }
      })

    },

    async initNodeForGraph() {
      const node = this.getNode()
      const {label, icon} = node.getAttrs()
      // 此处没有像initNodeForSidePanel一样直接使用import导入的路径，而转成base64，
      // 是因为直接使用路径时，graph.toPNG() 导出为图片时会丢失节点图片
      // https://antv-x6.gitee.io/zh/docs/tutorial/epilog#%E5%AF%BC%E5%87%BA%E5%9B%BE%E7%89%87%E6%A0%B7%E5%BC%8F%E7%BC%BA%E5%A4%B1
      this.iconSrc = await this.getBase64ImgSrc(icon['xlink:href'])
      this.label = label.text

      const nodeListeners = node.listeners
      const listenerKeys = Object.keys(nodeListeners)
      if(!listenerKeys.find(key => key === 'highlight')) {
        node.on("highlight", (options) => {
          this.highlight(options)
        })
      }

      if(!listenerKeys.find(key => key === 'unhighlight')) {
        node.on("unhighlight", () => {
          this.unhighlight()
        })
      }

      if (!listenerKeys.find(key => key === 'change:data')) {
        node.on("change:data", (e) => {
          const { current } = e
          this.label = current.dialogData?.name
        })
      }

      // console.log('node listeners', node.listeners)
    },

    initNodeForSidePanel() {
      this.iconSrc = this.nodeData.iconSrc
      this.label = this.nodeData.label
      this.$refs['customImage'].addEventListener('dragstart', this.handleDragStart.bind(this))
    },

    handleDragStart(e) {
      e.dataTransfer.setData('Text', JSON.stringify({
        ...this.nodeData,
        width: this.$refs.customImage.getBoundingClientRect().width,
        height: this.$refs.customImage.getBoundingClientRect().height
      }))
    },

    highlight(options) {
      this.isHighlight = true
    },

    unhighlight() {
      this.isHighlight = false
    }
  }
}
</script>

<style scoped lang="scss">
/*
  必须使用行内样式，否则将Graph导出为图片时 会导致样式丢失
  具体参见：
  https://antv-x6.gitee.io/zh/docs/tutorial/epilog#%E5%AF%BC%E5%87%BA%E5%9B%BE%E7%89%87%E6%A0%B7%E5%BC%8F%E7%BC%BA%E5%A4%B1
 */
.highlight-default {
  box-sizing: border-box;
  border: solid 2px red;
  border-radius: 7px;
  position: relative;
  animation: blink linear;
}
</style>
